Page({
  data: {
      sortedMedicines: new Array(15).fill(null),
      targetMedicines: [], // 待分拣的目标药品
      medicines: [],
      timeLeft: 50,
      timer: null,
      currentIndex: 0,
      showTip: false,
      tipMessage: '',
      scrollTop: 0
  },
  onLoad() {
      this.startGame();
      this.startAutoScroll();
  },
  startGame() {
      // 生成 30 种药品
      const allMedicines = [];
      for (let i = 1; i <= 30; i++) {
          allMedicines.push({ name: `药品${i}`, image: `/pages/img/${i}.png`, flipped: false });
      }
      console.log(allMedicines);
      // 复制一份药品数组用于生成目标药品
      const targetMedicinesArray = [...allMedicines];
      // 随机打乱目标药品数组顺序
      const shuffledTargetMedicines = this.shuffleArray(targetMedicinesArray);
      // 从打乱后的目标药品数组中选取 15 个作为目标药品
      const targetMedicines = shuffledTargetMedicines.slice(0, 15);

      // 随机打乱右侧药品数组顺序
      const shuffledMedicines = this.shuffleArray(allMedicines);

      this.setData({
          medicines: shuffledMedicines,
          targetMedicines,
          sortedMedicines: new Array(15).fill(null),
          timeLeft: 50,
          currentIndex: 0
      });
      // 开始计时
      this.startTimer();
  },
  shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
  },
  startTimer() {
      const timer = setInterval(() => {
          let timeLeft = this.data.timeLeft;
          timeLeft--;
          this.setData({
              timeLeft
          });
          if (timeLeft <= 0) {
              clearInterval(timer);
              this.gameOver();
          }
      }, 1000);
      this.setData({
          timer
      });
  },
  selectMedicine(e) {
      const selectedMedicine = e.currentTarget.dataset.medicine;
      let sortedMedicines = this.data.sortedMedicines;
      let currentIndex = this.data.currentIndex;
      let showTip = false;
      let tipMessage = '';
      const targetMedicines = this.data.targetMedicines;

      if (this.data.timeLeft > 0 && currentIndex < 15) {
          if (selectedMedicine.name === targetMedicines[currentIndex].name) {
              sortedMedicines[currentIndex] = selectedMedicine;
              this.setData({
                  sortedMedicines
              });
              currentIndex++;
              this.setData({
                  currentIndex
              });
              this.scrollToNewMedicine();
              showTip = true;
              tipMessage = '分拣成功！';

              // 检查是否提前完成游戏
              if (currentIndex === 15) {
                  clearInterval(this.data.timer);
                  this.gameOver();
              }
          } else {
              showTip = true;
              tipMessage = '选择错误，请重新选择！';
          }
      } else {
          if (this.data.timeLeft <= 0) {
              tipMessage = '时间已到，分拣失败！';
          } else {
              tipMessage = '没有空位了，分拣失败！';
          }
          showTip = true;
      }

      this.setData({
          showTip,
          tipMessage
      });

      // 提示信息显示一段时间后隐藏
      setTimeout(() => {
          this.setData({
              showTip: false
          });
      }, 2000);
  },
  scrollToNewMedicine() {
      const query = wx.createSelectorQuery();
      query.select('.scrollable').boundingClientRect();
      query.select('.medicine-boxes').boundingClientRect();
      query.exec((res) => {
          const scrollableHeight = res[0].height;
          const boxesHeight = res[1].height;
          if (boxesHeight > scrollableHeight) {
              this.setData({
                  scrollTop: boxesHeight - scrollableHeight
              });
          }
      });
  },
  gameOver() {
      const sortedCount = this.data.sortedMedicines.filter(item => item).length;
      const usedTime = 50 - this.data.timeLeft;
      wx.navigateTo({
          url: `/pages/GameOver/GameOver?sortedCount=${sortedCount}&usedTime=${usedTime}`
      });
  },
  onUnload() {
      clearInterval(this.data.timer);
  },
  flipMedicine(e) {
      const index = e.currentTarget.dataset.index;
      let medicines = this.data.medicines;
      medicines[index].flipped = true;
      this.setData({
          medicines
      });

      setTimeout(() => {
          medicines[index].flipped = false;
          this.setData({
              medicines
          });
      }, 5000);
  },
  startAutoScroll() {
      setInterval(() => {
          const scrollTop = this.data.scrollTop;
          this.setData({
              scrollTop: scrollTop + 1
          });
      }, 50);
  },
  onImageError(e) {
      console.log('图片加载失败:', e.detail.errMsg);
  },
  onImageLoad(e) {
      console.log('图片加载成功');
  }
})    